<template>
  <div>
    <el-form :model="productForm" :rules="rules" ref="productForm" label-width="120px" class="product-form" style="width:600px">
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="productForm.name" placeholder="请输入产品名称"></el-input>
      </el-form-item>
      
      <el-form-item label="产品类别" prop="category">
        <el-select v-model="productForm.category" placeholder="请选择产品类别">
          <el-option label="速冻类" value="速冻类"></el-option>
          <el-option label="半成品类" value="半成品类"></el-option>
          <el-option label="即食类" value="即食类"></el-option>
          <el-option label="即热类" value="即热类"></el-option>
          <el-option label="即配类" value="即配类"></el-option>
          <el-option label="即烹类" value="即烹类"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="供应商" prop="supplier_id">
        <el-select v-model="productForm.supplier_id" placeholder="请选择供应商" @change="handleSupplierChange">
          <el-option 
            v-for="item in suppliers" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="净重" prop="net_weight">
        <el-input v-model="productForm.net_weight" placeholder="例如: 200g/盒"></el-input>
      </el-form-item>
      
      <el-form-item label="保质期" prop="shelf_life">
        <el-input-number v-model="productForm.shelf_life" :min="1" :max="365" :step="1"></el-input-number>
        <span class="unit">天</span>
      </el-form-item>
      
      <el-form-item label="储存条件" prop="storage_conditions">
        <el-input 
          type="textarea" 
          :rows="2" 
          v-model="productForm.storage_conditions" 
          placeholder="请输入储存条件 (例如: -18°C以下冷冻保存)">
        </el-input>
      </el-form-item>
      
      <el-form-item label="营养信息" prop="nutrition_info">
        <el-input 
          type="textarea" 
          :rows="3" 
          v-model="productForm.nutrition_info_text" 
          placeholder="请输入营养信息 (例如: 蛋白质 10g, 脂肪 5g, 碳水化合物 20g)"
          @input="handleNutritionInfoChange">
        </el-input>
      </el-form-item>
      
      <el-form-item label="产品图片" prop="image_url">
        <el-upload
          action="/api/upload"
          list-type="picture-card"
          :multiple="false"
          :on-success="handleUploadSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog v-model="dialogVisible" size="tiny">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      
      <el-form-item label="产品描述" prop="description">
        <el-input type="textarea" :rows="4" v-model="productForm.description" placeholder="请输入产品描述"></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm('productForm')">保存</el-button>
        <el-button @click="resetForm('productForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      productForm: {
        name: '',
        category: '',
        supplier_id: '',
        supplier: '',
        net_weight: '',
        shelf_life: 30,
        storage_conditions: '',
        nutrition_info: {},
        nutrition_info_text: '',
        image_url: '',
        description: '',
        status: 'active'
      },
      
      suppliers: [],
      
      rules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择产品类别', trigger: 'change' }
        ],
        supplier_id: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        storage_conditions: [
          { required: true, message: '请输入储存条件', trigger: 'blur' }
        ],
        shelf_life: [
          { required: true, message: '请输入保质期', trigger: 'blur' }
        ]
      },
      
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  
  created() {
    // 获取供应商列表
    this.getSuppliers()
    
    // 如果有指定的供应商，则预选中
    const supplierId = this.$route.query.supplierId
    if (supplierId) {
      this.productForm.supplier_id = supplierId
      this.handleSupplierChange(supplierId)
    }
  },
  
  methods: {
    getSuppliers() {
      // 实际API调用
      axios.get('/api/suppliers').then(response => {
        if (response.data.status === 'success') {
          this.suppliers = response.data.items.map(item => ({
            value: item.id.toString(),
            label: item.name
          }))
        } else {
          this.$message.error(response.data.message || '获取供应商列表失败')
        }
      }).catch(err => {
        console.error('获取供应商列表失败:', err)
        this.$message.error('获取供应商列表失败')
      })
    },
    
    handleSupplierChange(supplierId) {
      // 根据供应商ID设置供应商名称
      const supplier = this.suppliers.find(item => item.value === supplierId)
      if (supplier) {
        this.productForm.supplier = supplier.label
      }
    },
    
    handleUploadSuccess(response, file, fileList) {
      if (response.status === 'success') {
        this.productForm.image_url = response.url
        this.$message.success('图片上传成功')
      } else {
        this.$message.error(response.message || '图片上传失败')
      }
    },
    
    handleRemove(file, fileList) {
      this.productForm.image_url = ''
    },
    
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    
    handleNutritionInfoChange(value) {
      // 尝试解析简单的营养信息文本为JSON对象
      try {
        const lines = value.split(',').map(item => item.trim());
        const nutrition = {};
        
        lines.forEach(line => {
          const parts = line.split(' ');
          if (parts.length >= 2) {
            const key = parts[0].trim();
            const value = parts[1].trim();
            if (key && value) {
              nutrition[key] = value;
            }
          }
        });
        
        this.productForm.nutrition_info = nutrition;
      } catch (e) {
        console.error('解析营养信息失败:', e);
        this.productForm.nutrition_info = {};
      }
    },
    
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 准备提交的数据
          const productData = {
            name: this.productForm.name,
            category: this.productForm.category,
            supplier_id: this.productForm.supplier_id,
            net_weight: this.productForm.net_weight,
            shelf_life: this.productForm.shelf_life,
            storage_conditions: this.productForm.storage_conditions,
            nutrition_info: this.productForm.nutrition_info,
            image_url: this.productForm.image_url,
            description: this.productForm.description,
            status: this.productForm.status
          };
          
          // 实际API调用
          axios.post('/api/products', productData)
          .then(response => {
            if (response.data.status === 'success') {
              this.$message({
                message: '产品添加成功',
                type: 'success'
              })
              this.$router.push('/product')
            } else {
              this.$message.error(response.data.message || '添加失败')
            }
          })
          .catch(err => {
            if (err.response && err.response.data && err.response.data.message) {
              this.$message.error(err.response.data.message)
            } else {
              console.error('添加产品失败:', err)
              this.$message.error('添加产品失败')
            }
          })
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    },
    
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
.product-form {
  margin: 0 auto;
}
.line {
  text-align: center;
  line-height: 36px;
}
.unit {
  margin-left: 5px;
  color: #606266;
}
</style> 